package com.qms.repast.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

import com.qms.repast.R;

import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * @author 泅渡者
 * @date 2018/9/21 0021
 * @describe: 启动界面防止白屏
 */
public class SplashActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {
	/**
	 * 权限集合
	 */
	private String[] permissions = {
			Manifest.permission.WRITE_EXTERNAL_STORAGE,
			Manifest.permission.READ_EXTERNAL_STORAGE,
			Manifest.permission.ACCESS_FINE_LOCATION};
	/**
	 * 授权请求码
	 */
	private static final int REQUEST_CODE = 1001;

	@Override
	protected void onCreate (@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);
		checkPermission();
	}

	/**
	 * 检查权限
	 */
	private void checkPermission () {
		if (EasyPermissions.hasPermissions(this, permissions)) {
			new Handler().postDelayed(new Runnable() {
				@Override
				public void run () {
					Intent intent = new Intent(SplashActivity.this, MainActivity.class);
					startActivity(intent);
					finish();
				}
			}, 2000);
		} else {
			EasyPermissions.requestPermissions(this, "软件必要的权限", REQUEST_CODE, permissions);
		}
	}

	@Override
	public void onRequestPermissionsResult (int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
	}

	/**
	 * 请求成功
	 *
	 * @param requestCode 请求码
	 * @param perms       成功授权集合
	 */
	@Override
	public void onPermissionsGranted (int requestCode, @NonNull List<String> perms) {
		if (requestCode == REQUEST_CODE) {
			Intent intent = new Intent(SplashActivity.this, MainActivity.class);
			startActivity(intent);
			finish();
		}
	}

	/**
	 * 请求失败
	 *
	 * @param requestCode 请求码
	 * @param perms       权限失败集合
	 */
	@Override
	public void onPermissionsDenied (int requestCode, @NonNull List<String> perms) {
		if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
			new AppSettingsDialog.Builder(this).build().show();
		}
	}

	@Override
	protected void onDestroy () {
		super.onDestroy();
	}
}
